import java.io.*;
import java.net.*;
import java.util.Scanner;


public class Client {
        Socket client;
        DataOutputStream out;
        int port;
        String name, serverIP;
        
        private class ClientThread implements Runnable{
         
        public void run(){
                try{
                        DataInputStream in = new DataInputStream(client.getInputStream());
                        while(true)
                                System.out.println(in.readUTF());
                }catch(SocketException se){
                        System.out.println("Connection lost");
                        connect(10);
                }catch(IOException io){
                        System.out.println("IO error while listening");
                //      connect(10);
                }
         }
 }

private void connect(int numTries){
        boolean connected = false;

        for(int i = 0; i < numTries; i++){
                System.out.println("Attempting to connect to " + serverIP + "...");
                try{
                        client = new Socket(serverIP, port);
                        new Thread(this.new ClientThread()).start();

                        out = new DataOutputStream(client.getOutputStream());
                        //out.writeUTF(name);   
                        connected = true;
                        break;
                }catch(ConnectException ce){
                        try {
                                Thread.sleep(2000);
                        } catch (InterruptedException ie) {
                                break;
                        };
                        System.out.println("Connection refused");
                }catch(IOException io){
                        System.out.println("IO problem at connect");
                }
        }
        if(connected)
                System.out.println("Connected to " + client.getRemoteSocketAddress() + ".");
        else
                System.out.println("Failed to connect");
}

Client(String username, String ip, int chosenPort){
        name = username;
        serverIP = ip;
        port = chosenPort;
        
        connect(10);
}

boolean sendData(String data){
        try{    
                out.writeUTF(name+": "+data);
        }catch(IOException io){
                System.out.println("Problem with IO");
                return false;
        }
        return true;
}



public static void main(String [] args){
        try{
                Client stuff = new Client("jimbo", "127.0.0.1", 7777);
                
                Scanner input = new Scanner(System.in); //this should be unnecessary in the actual game
                String message;
                while(true){
                        message = input.nextLine();
                        stuff.sendData(message);
                }

        }catch(Exception e){
                System.out.println("Something broke");
                e.printStackTrace();
        }
}
}